package com.nut.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.nut.pojo.Brand;
import com.nut.pojo.BrandExample;
import com.nut.pojo.Color;
import com.nut.pojo.ColorExample;
import com.nut.pojo.ProductExample;
import com.nut.pojo.ProductExample.Criteria;
import com.nut.pojo.ProductWithBLOBs;
import com.nut.pojo.Sku;
import com.nut.pojo.SkuExample;
import com.nut.pojo.Storage;
import com.nut.pojo.StorageExample;
import com.nut.service.brand.BrandServiceI;
import com.nut.service.color.ColorServiceI;
import com.nut.service.product.ProductServiceI;
import com.nut.service.sku.SkuServiceI;
import com.nut.service.storage.StorageServiceI;
import com.nut.utils.uploadImgUtils;

/**
 * @author Nut
 * @version 2018年8月10日 下午7:35:42
 * @TODO
 *
 */

@Controller
@RequestMapping("/product")
public class ProductController {

	@Resource
	BrandServiceI bsi;
	@Resource
	StorageServiceI ssi;
	@Resource
	ColorServiceI csi;
	@Resource
	ProductServiceI psi;
	@Resource
	SkuServiceI skusi;

	@RequestMapping("/list.do")
	public String list(ProductWithBLOBs product, ModelMap map) {
		ProductExample example = new ProductExample();
		example.setOrderByClause("id desc");

		Criteria createCriteria = example.createCriteria();
		createCriteria.andIsDelEqualTo(1);// 删除的商品不显示
		

		StringBuffer params = new StringBuffer();

		Page<ProductWithBLOBs> products = (Page<ProductWithBLOBs>) psi.queryByPages(product, example);

		// 因为images属性中存有多个图片，在预览时我们将images中的第一个图片显示出来
		// 在jsp页面使用fn标签，故此处不需要
		/*
		 * for (int i = 0; i < products.size(); i++) {
		 * products.get(i).setImages(products.get(i).getImages().split("//;")[0]
		 * ); }
		 */

		// 用来将brand的id替换成name
		Map<Integer, String> brandMap = new HashMap<>();
		Brand brand = new Brand();
		BrandExample be = new BrandExample();
		brand.setWithPage(0);
		List<Brand> brandList = bsi.query(brand, be);
		for (Brand b : brandList) {
			brandMap.put(b.getId(), b.getName());
		}
		// System.out.println(brandMap.toString());

		product.setUrl("list.do");
		product.setPages(products.getPages());
		product.setParams(params.toString());
		// 用来显示
		map.addAttribute("products", products);
		// 用来分页传递参数
		map.addAttribute("product", product);
		// 用来传递品牌名字
		map.addAttribute("brandsList", brandMap);
		return "product/list";
	}

	@RequestMapping(value = "/add.do", method = RequestMethod.GET)
	public String goAdd(ModelMap map) {
		// 查询品牌
		Brand brand = new Brand();
		brand.setWithPage(0);// 不使用分页
		BrandExample be = new BrandExample();
		be.createCriteria().andIsDelEqualTo(1);
		map.put("brands", bsi.query(brand, be));
		// 查询内存
		StorageExample se = new StorageExample();
		se.createCriteria().andIsDelEqualTo(1);
		map.put("storages", ssi.getStorages(se));
		// 查询颜色
		ColorExample ce = new ColorExample();
		ce.createCriteria().andIsDelEqualTo(1);
		map.put("colors", csi.getColors(ce));
		return "product/add";
	}

	/*
	 * 返回ajax 加注解@ResponseBody
	 */
	@RequestMapping(value = "/upload.do")
	@ResponseBody
	public String upload(MultipartFile img) {
		JSONObject json = new JSONObject();
		try {
			String str = uploadImgUtils.upload(img);
			json.put("error", 0);
			json.put("url", uploadImgUtils.IMGSERVER + str);
		} catch (Exception e) {
			json.put("error", 1);
			json.put("message", "上传失败");
		}
		return json.toString();
	}

	/*
	 * 多文件上传，在不知道form表单名字的时候，可使用
	 * 
	 * @RequestMapping(value="/add.do",method=RequestMethod.POST) public String
	 * doAdd(ProductWithBLOBs product,HttpServletRequest req){
	 * 
	 * List<String> names=new ArrayList<>(); MultipartHttpServletRequest
	 * request= (MultipartHttpServletRequest)req; List<MultipartFile> files =
	 * request.getFiles("image"); for (MultipartFile multipartFile : files) {
	 * try { names.add(MyUtils.upload(multipartFile)); } catch (Exception e) {
	 * // TODO Auto-generated catch block e.printStackTrace(); } }
	 * 
	 * product.setImages(names.toString().replaceAll("\\[",
	 * "").replaceAll("\\]", ""));
	 * System.out.println(productService.add(product));
	 * 
	 * return "redirect:list.do"; }
	 * 
	 */

	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
	public String doAdd(ProductWithBLOBs product, @RequestParam("imageList") MultipartFile[] imageList) {
		StringBuffer sb = new StringBuffer();
		try {
			for (int i = 0; i < imageList.length; i++) {
				sb.append(uploadImgUtils.upload(imageList[i]));
				sb.append(";");
			}

			product.setImages(sb.deleteCharAt(sb.length() - 1).toString());
			psi.add(product);
			// System.out.println(product.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:list.do";
	}

	@RequestMapping("del.do")
	public String doDel(int id) {
		ProductWithBLOBs product = new ProductWithBLOBs();
		product.setId(id);
		psi.delete(product);
		return "redirect:list.do";
	}

	@RequestMapping(value = "/edit.do", method = RequestMethod.GET)
	public String goEdit(int id, ModelMap map) {
		ProductWithBLOBs product = psi.queryOne(id);
		String[] images = product.getImages().split(";");
		String[] proStors = product.getStorageList().split(",");
		String[] proColors = product.getColorList().split(",");

		for (int i = 0; i < proStors.length; i++) {
			//System.out.println("stor:" + proStors[i] + ":");
		}
		for (int i = 0; i < proColors.length; i++) {
			//System.out.println("proColors:" + proColors[i] + ":");
		}

		// 用来存放查询到的商品
		map.put("product", product);
		// 用来存商品对用的图片数组
		map.put("imagesList", images);
		// 用来存商品对用的内存数组
		map.put("storList", proStors);
		// 用来存商品对用的颜色数组
		map.put("colorList", proColors);

		// 查询品牌
		Brand brand = new Brand();
		brand.setWithPage(0);// 不使用分页
		BrandExample be = new BrandExample();
		be.createCriteria().andIsDelEqualTo(1);
		// 查询内存
		StorageExample se = new StorageExample();
		se.createCriteria().andIsDelEqualTo(1);
		// 查询颜色
		ColorExample ce = new ColorExample();
		ce.createCriteria().andIsDelEqualTo(1);

		// 用来存全部的品牌名
		map.put("brands", bsi.query(brand, be));
		// 内存
		map.put("storages", ssi.getStorages(se));
		// 颜色
		map.put("colors", csi.getColors(ce));

		return "product/edit";
	}

	@RequestMapping(value = "/edit.do", method = RequestMethod.POST)
	public String doEdit(ProductWithBLOBs product, @RequestParam("imageList") MultipartFile[] imageList) {
		StringBuffer sb = new StringBuffer();
		try {
			for (int i = 0; i < imageList.length; i++) {
				sb.append(uploadImgUtils.upload(imageList[i]));
				sb.append(";");
			}

			product.setImages(sb.deleteCharAt(sb.length() - 1).toString());
			//System.out.println(product.toString());
			psi.update(product);
			// System.out.println(product.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:list.do";
	}

	@RequestMapping("/editIsShow.do")
	public String doEditIsShow(String id) {
		//System.out.println("###" + id + "####");
		ProductWithBLOBs product = new ProductWithBLOBs();
		product = psi.queryOne(Integer.valueOf(id));
		if(product.getIsShow() == 1){
			product.setIsShow(0);
		}else{
			product.setIsShow(1);
		}
		psi.update(product);
		
		return "redirect:list.do";
	}
	
	@RequestMapping("/details.do")
	public String details(String id,ModelMap map){
		System.out.println("id:::::"+id);
		map.addAttribute("id", id);
		return "product/product";
		//return "";
	}
	

	@RequestMapping("/getProduct.do")
	@ResponseBody
	public ProductWithBLOBs getProduct(int id) {
		ProductWithBLOBs product = psi.queryOne(id);
		
		ColorExample colorExample = new ColorExample();
		StorageExample storageExample = new StorageExample();
		List<Integer> colors = new ArrayList<>();
		List<Integer> storages = new ArrayList<>();
		String[] colorarr = product.getColorList().split(",");
		for (String string : colorarr) {
			colors.add(Integer.parseInt(string));
		}
		colorExample.createCriteria().andIdIn(colors);
		List<Color> colorlist = csi.getColors(colorExample);
		
		String[] storagearr = product.getStorageList().split(",");
		for (String string : storagearr) {
			storages.add(Integer.parseInt(string));
		}
		storageExample.createCriteria().andIdIn(storages);
		List<Storage> storagelist = ssi.getStorages(storageExample);
		
		product.setColors(colorlist);
		product.setStorages(storagelist);
		SkuExample skuExample = new SkuExample();
		skuExample.createCriteria().andProductIdEqualTo(id);
		List<Sku> skus = skusi.query(skuExample);
		product.setSkus(skus);
		return product;
	}

}